import { DataSource } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { config } from 'dotenv';
import { User } from '../../src/users/entities/user.entity';
import { Device } from '../../src/devices/entities/device.entity';
import { Task } from '../../src/tasks/entities/task.entity';
import { TaskTemplate } from '../../src/tasks/entities/task-template.entity';
import { TaskCategory } from '../../src/tasks/entities/task-category.entity';
import { Content } from '../../src/contents/entities/content.entity';
import { Tag } from '../../src/tags/entities/tag.entity';
import { Attachment } from '../../src/contents/entities/attachment.entity';
import { ContentTagMapping } from '../../src/tags/entities/content-tag-mapping.entity';
import { UserRole, DeviceStatus, TaskStatus, TaskType } from '../../src/common/enums';

async function setupTestDatabase() {
  // Load environment variables
  config();
  const configService = new ConfigService();

  // Create a temporary connection to postgres database
  const tempDataSource = new DataSource({
    type: 'postgres',
    host: configService.get('DB_HOST'),
    port: configService.get('DB_PORT'),
    username: configService.get('DB_USERNAME'),
    password: configService.get('DB_PASSWORD'),
    database: 'postgres',
  });

  try {
    await tempDataSource.initialize();

    // Drop active connections to the test database
    await tempDataSource.query(`
      SELECT pg_terminate_backend(pg_stat_activity.pid)
      FROM pg_stat_activity
      WHERE pg_stat_activity.datname = 'api_webservice_test'
      AND pid <> pg_backend_pid();
    `);

    // Drop test database if it exists
    await tempDataSource.query('DROP DATABASE IF EXISTS api_webservice_test;');

    // Create test database
    await tempDataSource.query('CREATE DATABASE api_webservice_test;');

    // Close temporary connection
    await tempDataSource.destroy();

    // Create a connection to the test database
    const testDataSource = new DataSource({
      type: 'postgres',
      host: configService.get('DB_HOST'),
      port: configService.get('DB_PORT'),
      username: configService.get('DB_USERNAME'),
      password: configService.get('DB_PASSWORD'),
      database: 'api_webservice_test',
      entities: [
        User,
        Device,
        Task,
        TaskTemplate,
        TaskCategory,
        Content,
        Tag,
        Attachment,
        ContentTagMapping,
      ],
      synchronize: false,
    });

    await testDataSource.initialize();

    // Drop existing enum types if they exist
    await testDataSource.query(`
      DO $$ BEGIN
        DROP TYPE IF EXISTS users_role_enum CASCADE;
        DROP TYPE IF EXISTS device_status_enum CASCADE;
        DROP TYPE IF EXISTS task_status_enum CASCADE;
        DROP TYPE IF EXISTS task_type_enum CASCADE;
      EXCEPTION
        WHEN others THEN null;
      END $$;
    `);

    // Create enum types
    await testDataSource.query(`CREATE TYPE users_role_enum AS ENUM ('user', 'admin');`);
    await testDataSource.query(
      `CREATE TYPE device_status_enum AS ENUM ('active', 'lost', 'retired');`,
    );
    await testDataSource.query(
      `CREATE TYPE task_status_enum AS ENUM ('not_start', 'completed', 'removed');`,
    );
    await testDataSource.query(`CREATE TYPE task_type_enum AS ENUM ('single', 'global');`);

    // Synchronize database schema
    await testDataSource.synchronize(true);

    // Close test database connection
    await testDataSource.destroy();

    console.log('Test database setup completed successfully');
  } catch (error) {
    console.error('Error setting up test database:', error);
    process.exit(1);
  }
}

//setupTestDatabase();
